//package org.example.bootvue.controller;
//
//import org.example.bootvue.entity.Result;
//import org.example.bootvue.utils.AliOssUtil;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.File;
//import java.io.IOException;
//import java.util.UUID;
//
//@RestController
//public class FileUploadController {
//    @PostMapping("/upload")
//public Result<String> fileUpload(MultipartFile file) throws Exception {
//        //把文件内容存储到本地云盘
//        String fileName = file.getOriginalFilename();
//        //保证文件名字唯一
//        String filename= UUID.randomUUID().toString()+"."+fileName.substring(fileName.lastIndexOf("."));
//       // file.transferTo(new File("D:/BaiduNetdiskDownload"+filename));
//        String url=AliOssUtil.uploadFile(fileName,file.getInputStream());
//        return Result.success(url);
//    }
//}
package org.example.bootvue.controller;

import org.example.bootvue.entity.Result;
import org.example.bootvue.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
public class FileUploadController {

    // 允许上传的文件类型白名单
    private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList(
            "image/jpeg", "image/png", "image/gif",
            "application/pdf", "text/plain"
    );

    // 最大文件大小限制（10MB）
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    @PostMapping("/upload")
    public Result<String> fileUpload(MultipartFile file) {
        // 1. 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要上传的文件");
        }

        // 2. 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return Result.error("文件大小不能超过10MB");
        }

        // 3. 检查文件类型
        if (!ALLOWED_FILE_TYPES.contains(file.getContentType())) {
            return Result.error("不支持的文件类型");
        }

        // 4. 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        try {
            // 5. 上传到阿里云OSS
            String url = AliOssUtil.uploadFile(uniqueFileName, file.getInputStream());
            return Result.success(url);

        } catch (IOException e) {
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error("系统错误: " + e.getMessage());
        }
    }
}